﻿using Microsoft.CodeAnalysis;

namespace ExampleIncrementalGenerator
{
    [Generator(LanguageNames.CSharp)]
    public class B_读取csproj项目文件的配置属性 : IIncrementalGenerator
    {
        public void Initialize(IncrementalGeneratorInitializationContext context)
        {
            context.RegisterImplementationSourceOutput(context.AnalyzerConfigOptionsProvider,
                (productionContext, provider) =>
                {
                    var text = string.Empty;

                    // 通过 csproj 的 PropertyGroup 里面获取
                    // 需要将可见的属性名，放入到 CompilerVisibleProperty 里面
                    // 需要加上 `build_property.` 前缀
                    if (provider.GlobalOptions.TryGetValue("build_property.MyCustomProperty", out var myCustomProperty))
                    {
                        text += $"{myCustomProperty} ";
                    }

                    var code = $@"
    using System;
    namespace ConsoleApp1
    {{
        public static class Foo
        {{
            public static void F1()
            {{
                Console.WriteLine($""{text}"");
            }}
        }}
    }}";
                    productionContext.AddSource("Demo", code);
                });
        }
    }
}
